package com.android.lovely.ui.activity

import android.os.Bundle
import android.os.SystemClock
import androidx.activity.addCallback
import androidx.core.os.bundleOf
import androidx.core.view.isVisible
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.whenResumed
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import coil.load
import com.android.lovely.R
import com.android.lovely.api.service.userService
import com.android.lovely.const.CreatedRoleRefresh
import com.android.lovely.const.FinishCreateRole
import com.android.lovely.data.ParameterValue
import com.android.lovely.databinding.ActivityCreateRolePreviewBinding
import com.android.lovely.databinding.ItemKeyNormalWordBinding
import com.android.lovely.databinding.ItemPreviewPhotoBinding
import com.android.lovely.ext.loadWithPlaceholder
import com.android.lovely.framework.BaseAdapter
import com.android.lovely.framework.BaseMvvmActivity
import com.android.lovely.room.role.CacheRoleServer
import com.android.lovely.room.role.CacheRoleServer.observeRole
import com.android.lovely.room.role.CreateRoleDataBase
import com.android.lovely.room.role.NewCard
import com.android.lovely.ui.dialog.UpLoadDialog
import com.android.lovely.ui.dialog.showLovelyDialog
import com.android.lovely.ui.fragment.role.CreateRoleBaseFragment
import com.android.lovely.ui.fragment.role.KeyWordAdapter
import com.android.lovely.ui.viewmodel.CreateRolePreviewViewModel
import com.android.lovely.user.UserManager
import com.google.android.flexbox.FlexboxLayoutManager
import com.kotlin.extensions.bus.FlowBus
import com.kotlin.extensions.bus.flowOf
import com.kotlin.extensions.bus.post
import com.kotlin.extensions.context.ContextExt.startPageClearTop
import com.kotlin.extensions.coroutine.CoroutineExt.launchSafety
import com.kotlin.extensions.view.ViewExt.addStatusBarMarginTop
import com.kotlin.extensions.view.ViewExt.clickable
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach

/**
 *
 * @author why
 * @date 2025/4/8 01:22
 */
class CreateRolePreviewActivity : BaseMvvmActivity<ActivityCreateRolePreviewBinding, CreateRolePreviewViewModel>() {


    var quickMode = false
    var id = -1

    val adapter by lazy {
        KeyTagAdapter()
    }

    val photoAdapter by lazy {
        PhotoAdapter()
    }
    override fun initView(savedInstanceState: Bundle?) {
        id = intent.getIntExtra("role_id", SystemClock.elapsedRealtime().toInt())
        quickMode = intent.getBooleanExtra("quick_mode", false)

        viewModel.id = id
        mBinding.flTop.addStatusBarMarginTop()

        mBinding.rvKeyword.layoutManager = FlexboxLayoutManager(this)
        mBinding.rvKeyword.adapter = adapter
        mBinding.rvPhoto.layoutManager = LinearLayoutManager(this, RecyclerView.HORIZONTAL, false)
        mBinding.rvPhoto.adapter = photoAdapter

        mBinding.preview.text =
            if (quickMode) getString(R.string.next) else getString(R.string.submit)
        mBinding.clPhoto.isVisible = !quickMode
        mBinding.clNsfw.isVisible = !UserManager.isC()

        mBinding.back.clickable {
            onBackPressedDispatcher.onBackPressed()
        }
        mBinding.ivDelete.clickable {
            delete()
        }
        mBinding.preview.clickable {
            submit()
        }
        onBackPressedDispatcher.addCallback(this) {
            onBackDialog()
        }
        FlowBus.flowOf<FinishCreateRole>().onEach {
            finish()
        }.launchIn(lifecycleScope)

        initOnClick()

        lifecycleScope.observeRole(id) {
            viewModel.createRole = it
            mBinding.apply {
                ivAvatar.loadWithPlaceholder(it.avatar, R.drawable.icon_default_avatar)

                tvName.text = it.nickName
                tvGender.text =
                    resources.getString(if (it.gender == 1) R.string.male else if (it.gender == 2) R.string.female else R.string.unknown)
                tvType.text = if(it.category == 1) getString(R.string.fantasy) else getString(R.string.real)
                tvNsfw.isSelected = it.nsfw
                tvPublic.isSelected = it.public
                tvIntroduction.text = it.introduction
                tvCharacterDescription.text = it.description
                tvScenario.text = it.scenario
                tvFirstMessage.text = it.firstMessage
                tvDialogExample.text = it.chatExample
                mBinding.load.isVisible = it.status == 1
                mBinding.errorLoad.isVisible = it.status == 3
                adapter.updateList(it.keywords)
                photoAdapter.updateList(it.cards)
            }
        }
        viewModel.getCard(id)

    }

    private fun initOnClick() {
        mBinding.llAvatar.clickable {
            CreateRoleActivity.startEdit(
                this,
                0,
                id,
                true,
                quickMode
            )
        }
        mBinding.llGender.clickable {
            CreateRoleActivity.startEdit(
                this,
                0,
                id,
                true,
                quickMode
            )
        }
        mBinding.llType.clickable {
            CreateRoleActivity.startEdit(
                this,
                0,
                id,
                true,
                quickMode
            )
        }
        mBinding.tvNsfw.clickable {
            mBinding.tvNsfw.isSelected = !mBinding.tvNsfw.isSelected
            viewModel.updateRole {
                nsfw = mBinding.tvNsfw.isSelected
            }
        }
        mBinding.tvPublic.clickable {
            mBinding.tvPublic.isSelected = !mBinding.tvPublic.isSelected
            viewModel.updateRole {
                public = mBinding.tvPublic.isSelected
            }
        }
        mBinding.slIntroduction.clickable {
            CreateRoleActivity.startEdit(
                this,
                1,
                id,
                true,
                quickMode
            )
        }
        mBinding.slKeywords.clickable {
            CreateRoleActivity.startEdit(
                this,
                1,
                id,
                true,
                quickMode
            )
        }
        mBinding.clCharacter.clickable {
            CreateRoleActivity.startEdit(
                this,
                2,
                id,
                true,
                quickMode
            )
        }
        mBinding.clScenario.clickable {
            CreateRoleActivity.startEdit(
                this,
                2,
                id,
                true,
                quickMode
            )
        }
        mBinding.clFirst.clickable {
            CreateRoleActivity.startEdit(
                this,
                3,
                id,
                true,
                quickMode
            )
        }
        mBinding.clDialog.clickable {
            CreateRoleActivity.startEdit(
                this,
                3,
                id,
                true,
                quickMode
            )
        }

        mBinding.clPhoto.clickable {
            CreateRoleActivity.startEdit(
                this,
                4,
                id,
                true,
                quickMode
            )
        }
    }

    private fun onBackDialog() {
        if ((viewModel.createRole?.createId?:0) > 0) {
            finish()
            return
        }
        showLovelyDialog {
            setDialogTitle(getString(R.string.create_role_back, "1"))
            setNegativeButton (getString(R.string.quit)) {
                dismiss()
            }
            setPositiveButton(getString(R.string.btn_continue)) {
                lifecycleScope.launchSafety {
                    finish()
                }
            }
        }
    }

    private fun submit() {
        if (quickMode) {
            CreateRoleActivity.startEdit(
                this,
                4,
                id,
                false,
                this.quickMode
            )
            return
        }
        showLovelyDialog {
            setDialogTitle(getString(R.string.role_submit_18))
            setPositiveButton {
                lifecycleScope.launchSafety {
                    val dialog = UpLoadDialog().apply {
                        arguments = bundleOf("isEdit" to false,
                            "role_id" to viewModel.id)
                    }
                    dialog.show(supportFragmentManager)
                    runCatching {
                        val success = viewModel.createRole()
                        dialog.dismissAllowingStateLoss()
                        if (success) {
                            lifecycle.whenResumed {
                               startPageClearTop<HomeActivity>("position" to 3,
                                    "role" to (viewModel.createRole?.public ?: true)
                                )
                                FlowBus.post(CreatedRoleRefresh())
                                FlowBus.post(FinishCreateRole())
                            }
                        }
                    }
                }
            }
        }
    }

    private fun delete() {
        showLovelyDialog {
            setDialogTitle(getString(R.string.delete_role))
            setPositiveButton (getString(R.string.btn_continue)) {
                lifecycleScope.launchSafety {
                    if (id > 0) {
                        runCatching {
                            userService.deleteRole(mapOf("draft_id_list" to id.toString()))
                            FlowBus.post(CreatedRoleRefresh())
                        }
                    }
                    FlowBus.post(FinishCreateRole())
                    CacheRoleServer.remove(id)
                    CreateRoleDataBase.dao.delete(id)
                    finish()
                }
            }
            setNegativeButton (getString(R.string.quit)) {

            }
        }
    }
}

class PhotoAdapter() : BaseAdapter<NewCard, ItemPreviewPhotoBinding>(){
    override fun bindViewWithHolderDetails(
        holder: ViewHolder,
        item: NewCard?,
        binding: ItemPreviewPhotoBinding,
        position: Int
    ) {
        item ?: return
        binding.image.load(item.localePath.ifEmpty { item.url }) { crossfade(true) }
    }
}

class KeyTagAdapter : BaseAdapter<String, ItemKeyNormalWordBinding>() {
    override fun bindViewWithHolderDetails(
        holder: ViewHolder,
        item: String?,
        binding: ItemKeyNormalWordBinding,
        position: Int
    ) {
        binding.tvKey.text = item ?: ""
        binding.tvKey.isSelected = true
    }
}